package sk.tramtatiri;

import org.apache.wicket.IResourceListener;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.markup.html.WebResource;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.protocol.http.RequestUtils;
import org.apache.wicket.util.resource.AbstractStringResourceStream;
import org.apache.wicket.util.resource.IResourceStream;

import ofc4j.model.Chart;

/**
 * Panel for showing a Flash Chart
 */
public class OpenFlashChart extends Panel implements IResourceListener {

  static final ResourceReference SWF_RESOURCE = new ResourceReference(OpenFlashChart.class, "open-flash-chart.swf" );

  final WebResource jsonResource;
  final SWFObject swf;

  public OpenFlashChart(String id, final String width, final String height, final Chart chart) {
    this(id, width, height, new Model<String>(chart.toString()));
  }

  public OpenFlashChart(String id, final int width, final int height, final Chart chart) {
    this(id, String.valueOf(width), String.valueOf(height), new Model<String>(chart.toString()));
  }

  public OpenFlashChart(String id, final int width, final int height, IModel<String> jsonModel) {
    this(id, String.valueOf(width), String.valueOf(height), jsonModel);
  }

  public OpenFlashChart(String id, final String width, final String height, final IModel<String> jsonModel) {
    super(id);
    
    this.setOutputMarkupId(true);
    final IResourceStream json = new AbstractStringResourceStream("text/plain") {
      @Override
      public String getString() {
        return jsonModel.getObject();
      }
    };

    jsonResource = new WebResource() {
      @Override
      public IResourceStream getResourceStream() {
        return json;
      }
    };
    jsonResource.setCacheable(false);

    String swfURL = RequestUtils.toAbsolutePath( urlFor(SWF_RESOURCE).toString() );
    add(swf = new SWFObject( swfURL, width, height, "9.0.0"));
    
  }


  private String getUrlForJson() {
    CharSequence dataPath = RequestCycle.get().urlFor(OpenFlashChart.this, IResourceListener.INTERFACE);
    return RequestUtils.toAbsolutePath( dataPath.toString() );
  }

  @Override
  protected void onBeforeRender() {
    swf.addParameter("data-file", getUrlForJson());
    super.onBeforeRender();
  }

  /**
   * Actually handle the request
   */
  public void onResourceRequested() {
    jsonResource.onResourceRequested();
  }
}

